using System;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using MediaPortal.GUI.Video;
//using MediaPortal.Video.Database;
using MediaPortal.Util;
using MediaPortal.Dialogs;
using MediaPortal.Player;
using System.Data;
using System.ComponentModel;
using c3o.Framework.Web;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text.RegularExpressions;

namespace MediaPortal.GUI.Rss
{
	public class GUIRssBaseWindow : GUIVideoBaseWindow
	{
		[SkinControlAttribute(200)]		protected GUIButtonControl bttnAddSite = null;
		[SkinControlAttribute(140)]		protected GUIButtonControl bttnDelete = null;
		[SkinControlAttribute(80)]		protected GUITextScrollUpControl detailbox = null;

		protected string xmlSection = "RSS";
		protected string ListMode = "Sites";
		protected OpmlOutline selectedOutline = null;
		protected Opml opmlList;
		protected Opml opmlFeeds;
		protected Opml opmlSearch;
		protected RssReader dtRss;
		protected string CurrentUrl = null;

		//protected GUIFacadeControl.ViewMode DefaultView = GUIFacadeControl.ViewMode.List;
		protected GUIFacadeControl.ViewMode DefaultView
		{
			get
			{
				MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings("MediaPortal.xml");
				return (GUIFacadeControl.ViewMode)xmlreader.GetValueAsInt(this.xmlSection, this.ListMode + ".ViewMode", (int)GUIFacadeControl.ViewMode.List);
			}
			set
			{
				MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings("MediaPortal.xml");
				xmlwriter.SetValue(this.xmlSection, this.ListMode + ".ViewMode", (int)value);
			}
		}

		protected string RootFolder = @"Feeds";
		protected string RssFileName = @"My.Feeds.opml.xml";
		protected string OpmlFileName = @"My.Search.opml.xml";

		protected string CurrentSite = null;
		
		protected override void OnPageLoad()
		{
			base.OnPageLoad();

			if (System.IO.File.Exists(this.RootFolder + @"\" + this.RssFileName))
			{
				this.opmlList = this.LoadOpml(this.RootFolder + @"\" + this.RssFileName);
			}
			else
			{
				this.opmlList = new Opml();
				this.opmlList.head.title = "Mediaportal Content Feed";
			}			

			// Load Site List
			this.ShowSites();

			this.CurrentSite = "";

			// Set Focus on List
			GUIControl.FocusControl(this.GetID, this.facadeView.GetID);
		}

		protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
		{
			base.OnClicked(controlId, control, actionType);

			if (control == this.btnViewAs) this.DefaultView = this.facadeView.View;
            if (control == this.bttnAddSite)
            {
                this.ShowOpmlSites();
            }
			if (control == this.facadeView) this.OnListView();
			//if (control == this.bttnAddSearchTag) this.AddSearchTag();
			if (control == this.bttnDelete) this.OnDelete();

//			base.OnClicked(controlId, control, actionType);
		}

		virtual protected void OnDelete()
		{
			switch (this.ListMode)
			{
				case "Sites.List":
					// Delete selected site
					this.DeleteRssFeed();
					break;
			}
		}

		public override void OnAction(Action action)
		{
			if (action.wID == Action.ActionType.ACTION_PREVIOUS_MENU)
			{
				if (this.ListMode == "Sites")
				{
					base.OnAction(action);
				}
				else
				{
					this.ShowSites();
				}
			}
			else
			{
				base.OnAction(action);
			}
			

			switch (action.wID)
			{
				case Action.ActionType.ACTION_STOP:
					this.OnStop();
					break;
				case Action.ActionType.ACTION_PLAY:
					this.OnPlay();
					break;
			}

			if (action.IsUserAction())
			{
				if (this.CurrentSite != "UKNova")
				{
					GUIListItem item = this.facadeView.SelectedListItem;
					if (item != null)
					{
						if (this.ListMode == "Sites.List")
						{
							this.detailbox.Label = item.DVDLabel;
						}
					}
				}
			}
		}

		protected virtual void OnStop()
		{

		}

		protected virtual void OnPlay()
		{

		}

		public void RefreshTitle()
		{
			GUIListItem item = facadeView.SelectedListItem;

			if (item != null)
			{
				GUIPropertyManager.SetProperty("#selecteditem", item.Label);
				GUIWindowManager.Process();
			}

		}


		virtual protected void OnListView()
		{
			GUIListItem item = this.facadeView.SelectedListItem;

			if (item != null)
			{
				this.selectedOutline = (OpmlOutline) item.TVTag as OpmlOutline;

				if (this.selectedOutline != null)
				{
					//this.detailbox.Label = "if (this.selectedOutline != null)";
					if (this.selectedOutline.body.opml == this.opmlFeeds) this.OnListViewOpmlSites();
					if (this.selectedOutline.body.opml == this.opmlSearch) this.OnListViewOpmlList();
					if (this.selectedOutline.body.opml == this.opmlList) this.OnListViewSites();
				}
				else
				{
					switch (this.ListMode)
					{
						case "Sites.List":
							this.OnListViewList();
							break;
					}
				}
			}
		}


		protected void OnListViewSites()
		{
			GUIListItem item = this.facadeView.SelectedListItem;

			if (item != null)
			{				
				this.CurrentSite = item.Label;
				this.CurrentUrl = item.Path;
				ShowSite();
			}
		}


		virtual protected void OnListViewList()
		{
		}



		protected void OnListViewOpmlList()
		{
			GUIListItem item = this.facadeView.SelectedListItem;

			if (item != null)
			{
				if (item.IsFolder)
				{
					if (item.Label == "..")
					{
						this.ListMode = "Sites.Opml.List";
						this.SelectOutline(this.opmlFeeds, this.selectedOutline.parent, GUIFacadeControl.ViewMode.List);
					}
					else
					{
						if (this.selectedOutline != null)
						{
							this.ListMode = "Sites.Opml.List";
							this.SelectOutline(this.opmlFeeds, this.selectedOutline, GUIFacadeControl.ViewMode.List);
						}
					}
				}
				else
				{
					// Select RSS Feed
					this.AddRssFeed(item.Path);
				}
			}
		}

		protected void OnListViewOpmlSites()
		{
			GUIListItem item = this.facadeView.SelectedListItem;

			if (item != null)
			{
				if (item.Label == "..")
				{
					this.ShowOpmlSites();
				}
				else
				{					
					this.SearchOpml(item.Path);
				}
			}
		}

		virtual protected void ShowSites()
		{
			this.ShowSites(true);
		}

		virtual protected void ShowSites(bool DoClear)
		{
			this.CurrentSite = null;
			this.bttnDelete.Disabled = true;
			this.bttnDelete.Label = "Delete";
			this.ListMode = "Sites";

			// Add UKNova
//			GUIListItem item = new GUIListItem();
//			item.Label = "UKNova";
//			item.IsFolder = true;
//			item.Path = "UKNova";
//			facadeView.Add(item);

			// Show Rss Feeds from OPML file
			this.SelectOutline(this.opmlList, null, this.DefaultView, DoClear);

			GUIControl.FocusControl(this.GetID, this.facadeView.GetID);
		}


		virtual protected void ShowSite()
		{
			ListMode = "Sites.List";
			this.bttnDelete.Disabled = false;
			this.bttnDelete.Label = "Delete Feed";

			if (this.selectedOutline != null)
			{
				if (this.selectedOutline.url != null && this.selectedOutline.url.Length > 0)
				{
					this.ShowRSS();
				}
				else
				{
					this.ListMode = "Sites.Opml.List";
					this.SelectOutline(this.opmlList, this.selectedOutline, this.DefaultView);
				}
			}

			GUIControl.FocusControl(this.GetID, this.facadeView.GetID);
		}
	

		protected void ShowOpmlSites()
		{
			this.ListMode = "Sites.Opml";

			string FileName = this.RootFolder + @"\" + this.OpmlFileName;

			if (System.IO.File.Exists(FileName))
			{
				this.bttnDelete.Disabled = true;
				this.bttnDelete.Label = "Delete";

				if (this.opmlFeeds == null) this.opmlFeeds = this.LoadOpml(FileName);

				this.SelectOutline(this.opmlFeeds, null, this.DefaultView);
			}
		}

	
		protected void SearchOpml(string url)
		{
			this.ListMode = "Sites.Opml.List";

			string Source = null;

			//// SVN version
			//// Cache The Page
            MediaPortal.Utils.Web.HTMLCache hc = new MediaPortal.Utils.Web.HTMLCache();

            hc.WebCacheInitialise();

            if (hc.LoadPage(new MediaPortal.Utils.Web.HTTPRequest(url)))
            {
                Source = hc.GetPage();
            }
            else
            {
                SiteReader sr = new SiteReader();
                Source = sr.ReadPage(url);
                hc.SavePage(new MediaPortal.Utils.Web.HTTPRequest(url), Source);
            }

            //// 0.2.2 version
            //MediaPortal.Utils.Web.HTMLCache hc = new MediaPortal.Utils.Web.HTMLCache();

            //MediaPortal.Utils.Web.HTMLCache.WebCacheInitialise();

            //if (MediaPortal.Utils.Web.HTMLCache.LoadPage(new Uri(url)))
            //{
            //    Source = MediaPortal.Utils.Web.HTMLCache.GetPage();
            //}
            //else
            //{
            //    SiteReader sr = new SiteReader();
            //    Source = sr.ReadPage(url);
            //    MediaPortal.Utils.Web.HTMLCache.SavePage(new Uri(url), Source);
            //}

			// Read rss feed into XmlDocument
			XmlDocument xml = new XmlDocument();
			xml.LoadXml(Source);

			if (xml.DocumentElement.Name == "opml")
			{
				this.opmlSearch = new Opml(xml);
				
				this.selectedOutline.Link(this.opmlSearch);
				
				this.SelectOutline(this.opmlFeeds, this.selectedOutline, this.DefaultView);
			}
		}

		protected void SelectOutline(Opml opml, OpmlOutline outline, GUIFacadeControl.ViewMode mode)
		{
			this.SelectOutline(opml, outline, mode, true);
		}

		protected void SelectOutline(Opml opml, OpmlOutline outline, GUIFacadeControl.ViewMode mode, bool DoClear)
		{
			this.selectedOutline = outline;

			if (DoClear)
			{
				GUIControl.ClearControl(this.GetID, facadeView.GetID);
				this.facadeView.View = mode;
			}

			if (outline != null)
			{
				GUIListItem item = new GUIListItem();
				item.Label = "..";
				item.Path = "..";
				item.IsFolder = true;
				item.IsRemote = false;
				item.IconImage = "defaultVideo.png";
				item.TVTag = outline;
				this.facadeView.Add(item);
			}
			

			// Show List
			this.ShowOutlines(opml);
		}
		
		protected void ShowOutlines(Opml opml)
		{
			this.bttnDelete.Disabled = true;
			this.bttnDelete.Label = "Delete";

			OpmlOutline[] list = null;
			if (selectedOutline == null)
			{
				list = opml.body.outlines;
			}
			else
			{
				list = selectedOutline.outlines;
			}

			foreach (OpmlOutline outline in list)
			{
				GUIListItem item = new GUIListItem();
				item.TVTag = outline;
				item.Label = outline.text;

				if (outline.image != null && outline.image.Length > 0)
				{
					this.DownloadAndCache(outline.image, outline.text);

					string coverArtImage = MediaPortal.Util.Utils.GetCoverArtName(Thumbs.MovieTitle, outline.text);
					string largeCoverArtImage = MediaPortal.Util.Utils.GetLargeCoverArtName(Thumbs.MovieTitle, outline.text);

					item.ThumbnailImage = coverArtImage;
					item.IconImage = coverArtImage;
					item.IconImageBig = largeCoverArtImage;
				}
				else
				{
					item.IconImage = "defaultVideo.png";
				}

				if (outline.url != null && outline.url.Length > 0)
				{
					item.IsFolder = false;
					item.Path = outline.url;
					item.IsRemote = true;
				}
				else
				{
					item.IsFolder = true;
					item.IsRemote = false;
					item.Path = "";
				}
				this.facadeView.Add(item);
			}

			GUIControl.FocusControl(this.GetID, this.facadeView.GetID);
		}

		protected Opml LoadOpml(string FileName)
		{
			Opml opml = null;

			if (System.IO.File.Exists(FileName))
			{				
				XmlDocument xml = new XmlDocument();
				xml.Load(FileName);
				opml = new Opml(xml);
				this.selectedOutline = null;
			}
			return opml;
		}


		protected void AddRssFeed()
		{
			string url = String.Empty;

			if (GetKeyboard(ref url))
			{
				if (url.Length > 0)
				{
					this.AddRssFeed(url);
				}
			}
		}
		
		protected void AddRssFeed(string url)
		{
			// Read info from url 
			RssReader dtRss = new RssReader(url);

			DataTable dt = dtRss.Header;

			if (dt.Rows.Count > 0)
			{
				foreach (DataRow row in dt.Rows)
				{
					string SiteName = row["title"].ToString();

					string image = null;

					if (dtRss.Header.Columns.Contains("itunes:image_href"))
					{
						 image = dtRss.Header.Rows[0]["itunes:image_href"].ToString();
					}

					this.opmlList.body.Add(new OpmlOutline(SiteName, "link", url, image, this.opmlList.body, null));

					this.opmlList.GetXml().Save(this.RootFolder + @"\" + this.RssFileName);

					this.ShowSites();
				}
			}
		}

		//protected void AddRssFeed(OpmlOutline outline)
		//{
		//    this.opmlList.body.Add(new OpmlOutline(SiteName, "link", url, image, this.opmlList.body, null));

		//    this.opmlList.GetXml().Save(this.RootFolder + @"\" + this.RssFileName);

		//    this.ShowSites();
		//}
				

		protected void DeleteRssFeed()
		{
			if (this.selectedOutline != null)
			{
				this.selectedOutline.Delete();
				//this.selectedOutline.text = "delete me";

				this.opmlList.GetXml().Save(this.RootFolder + @"\" + this.RssFileName);

				this.opmlList = this.LoadOpml(this.RootFolder + @"\" + this.RssFileName);

				this.ShowSites();
			}
		}
		


		protected void DownloadAndCache(string imageUrl, string title)
		{
			if (imageUrl.Length > 0)
			{
				string coverArtImage = MediaPortal.Util.Utils.GetCoverArtName(Thumbs.MovieTitle, title);
				string largeCoverArtImage = MediaPortal.Util.Utils.GetLargeCoverArtName(Thumbs.MovieTitle, title);

				if (!System.IO.File.Exists(coverArtImage))
				{
					string imageExtension;
					imageExtension = System.IO.Path.GetExtension(imageUrl);
					if (imageExtension.Length > 0)
					{
						string temporaryFilename = "temp";
						temporaryFilename += imageExtension;
						MediaPortal.Util.Utils.FileDelete(temporaryFilename);

						MediaPortal.Util.Utils.DownLoadAndCacheImage(imageUrl, temporaryFilename);
						if (System.IO.File.Exists(temporaryFilename))
						{
							MediaPortal.Util.Picture.CreateThumbnail(temporaryFilename, coverArtImage, 128, 128, 0);
							MediaPortal.Util.Picture.CreateThumbnail(temporaryFilename, largeCoverArtImage, 512, 512, 0);
						}

						MediaPortal.Util.Utils.FileDelete(temporaryFilename);
					}
				}
			}
		}

		protected void OnPlayBackStopped(MediaPortal.Player.g_Player.MediaType type, int timeMovieStopped, string filename)
		{
			if (!g_Player.Playing)
			{
				g_Player.Release();
			}
		}

		protected void OnPlayBackEnded(MediaPortal.Player.g_Player.MediaType type, string filename)
		{
			if (!g_Player.Playing)
			{
				g_Player.Release();
			}
		}
			

		// Background Version
		public void ShowRSSAsc()
		{
			// Load Page in background
			BackgroundWorker worker = new BackgroundWorker();
			worker.DoWork += new DoWorkEventHandler(this.ShowRSS);
			worker.RunWorkerAsync();
		}
		public void ShowRSS(object sender, DoWorkEventArgs e) { this.ShowRSS(); }
		public void ShowRSS()
		{
			this.ListMode = "Sites.List";

			this.bttnDelete.Disabled = false;
			this.bttnDelete.Label = "Delete " + this.CurrentSite;

			if (this.selectedOutline != null)
			{
				//OpmlOutline outline = (OpmlOutline)this.facadeView.SelectedListItem.TVTag as OpmlOutline;

				string SiteName = this.selectedOutline.text;
				string SiteUrl = this.selectedOutline.url;
				string pattern = this.selectedOutline.search;
				string replacement = this.selectedOutline.replace;

				GUIPropertyManager.SetProperty("#selecteditem", "Loading " + SiteUrl + "...");
				GUIWindowManager.Process();

				GUIControl.ClearControl(this.GetID, facadeView.GetID);
				this.facadeView.View = this.DefaultView;

				GUIListItem item = new GUIListItem();
				item.Label = "..";
				item.IsFolder = true;
				item.IconImage = "defaultVideo.png";

				facadeView.Add(item);

				if (SiteUrl != null && SiteUrl.Length > 0)
				{
					SiteUrl = SiteUrl.Replace("AND", "&");

					GUIPropertyManager.SetProperty("#selecteditem", "Loading " + SiteUrl);

					// Read rss feed
					dtRss = new RssReader(SiteUrl, pattern, replacement);

					DataTable dt = dtRss.Detail;

					// Convert to view for sort and filter
					//DataView dv = new DataView(dt);

					// Set Filter
					//if (this.SearchString != null && this.SearchString.Length > 0)
					//{
					//    dv.RowFilter = " title like '%" + this.SearchString + "%' or description like '%" + this.SearchString + "'%";
					//}

					// Sort by pub date
					//                if (dtRss.Detail.Columns.Contains("pubDate"))
					//              {
					//                dv.Sort = "pubDate desc";
					//          }

					/// Load back into table
					//dt = dv.ToTable();

					foreach (DataRow row in dt.Rows)
					{
						string url = null;

						if (dt.Columns.Contains("enclosure_url")) url = row["enclosure_url"].ToString();

						if (url == null || url.Length == 0)
						{
							if (dt.Columns.Contains("link")) url = row["link"].ToString();
						}

						item = new GUIListItem();
						item.IsFolder = false;
						item.IconImage = "defaultVideo.png";
						item.Path = url;
						if (dt.Columns.Contains("title")) item.Label = row["title"].ToString();
						if (dt.Columns.Contains("description")) item.DVDLabel = row["description"].ToString();
						facadeView.Add(item);
					}
				}
				this.RefreshTitle();

				GUIControl.FocusControl(this.GetID, this.facadeView.GetID);				
			}
		}
	}
}